package vm

import "go-forth/pkg/forth"

const autoExtendedArea = 1024

type DataSpace struct {
	data     []forth.Token
	reserved int
}

func (d *DataSpace) Fetch(addr int) forth.Token {
	return d.data[addr]
}

func (d *DataSpace) Store(addr int, token forth.Token) {
	if diff := addr - len(d.data); diff >= 0 && addr < autoExtendedArea {
		d.data = append(d.data, make([]forth.Token, diff+1)...)
	}
	d.data[addr] = token
}

func (d *DataSpace) Append(token forth.Token) {
	d.data = append(d.data, token)
	d.reserved++
}

func (d *DataSpace) Reserved() int {
	return d.reserved
}

func (d *DataSpace) Capacity() int {
	return cap(d.data)
}

func (d *DataSpace) Reserve(n int) {
	if n > 0 {
		d.data = append(d.data, make([]forth.Token, n)...)
		d.reserved += n
	}
}

var _ forth.DataSpace = &DataSpace{}
